<template>
  <div class="SJCJ">
    <div class="query">
      <el-button size="small" type="warning" @click="todo"
        >手动数据采集</el-button
      >
      <el-button size="small" type="warning" @click="stop"
        >终止数据采集</el-button
      >
      数据库选择：
      <el-select v-model="query.dbId" placeholder="请选择" size="small">
        <el-option
          v-for="item in DbList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      时间：
      <el-date-picker
        size="small"
        v-model="value2"
        type="datetimerange"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        align="right"
        @change="time_change"
      >
      </el-date-picker>
      采集类型：
      <el-select v-model="query.addType" placeholder="请选择" size="small">
        <el-option label="新增+更新" value="0"> </el-option>
        <el-option label="新增" value="1"> </el-option>
        <el-option label="更新" value="2"> </el-option>
      </el-select>
    </div>
    <div class="main">
      <el-tree
        :data="TableTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="node_key"
        :props="defaultProps"
        @check="tree_change"
        ref="tree"
      >
      </el-tree>
    </div>
    <div class="msg" id="box_auto" ref="box_auto">
      <div v-for="(i, index) in isMsg" :key="index" class="msg_item">
        <span style="color: blue">服务器回应 {{ i.date | time }}</span
        ><br />
        <span>{{ i.msg }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: "",
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      value: "",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: "",
      TableTree: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      DbList: [],
      node_key: [],
      query: {
        dbId: "",
        addType: "",
        checkList: [],
        startTime: "",
        endTime: "",
      },
      // path: "ws://" + "172.16.33.16:7039" + "?tenant=T1&room=1&type=collect", // 玉龙
      path: "ws://" + "10.0.0.155:8006" + "?tenant=T1&room=1&type=collect", // 香格里拉
      socket: "",
      isMsg: [],
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  filters: {
    time(val) {
      if (val == null || val == "") {
        return "";
      } else {
        let d = new Date(val); // val 为表格内取到的后台时间
        let month =
          d.getMonth() + 1 < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;
        let day = d.getDate() < 10 ? "0" + d.getDate() : d.getDate();
        let hours = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
        let min = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
        let sec = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds();
        let times =
          d.getFullYear() +
          "-" +
          month +
          "-" +
          day +
          " " +
          hours +
          ":" +
          min +
          ":" +
          sec;
        return times;
      }
    },
  },
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {},
  updated() {},
  /**
   * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
   */
  mounted() {
    this.getDBList();
    this.getTreeList();
    this.init();
  },
  // 组件方法
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        let chat = this.$el.querySelector("#box_auto");
        chat.scrollTop = chat.scrollHeight;
      });
    },
    getDBList() {
      this.$get(baseUrl.jbIp + "/T1/api/v1/Platform/Collect/DbList").then(
        (res) => {
          this.DbList = res.data;
        }
      );
    },
    getTreeList() {
      this.$get(baseUrl.jbIp + "/T1/api/v1/Platform/Collect/TableTree").then(
        (res) => {
          var newList = [];
          for (var i in res.data) {
            var a = {
              id: "",
              label: res.data[i].tableDescription,
              children: [],
            };
            if (res.data[i].tableList) {
              for (var j in res.data[i].tableList) {
                a.children.push({
                  id: res.data[i].tableList[j].tableName,
                  label:
                    res.data[i].tableList[j].tableName +
                    "（" +
                    res.data[i].tableList[j].tableDescription +
                    "）",
                });
              }
            }
            newList.push(a);
          }
          this.TableTree = newList;
        }
      );
    },
    tree_change() {
      let arr = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      var newArr = arr.filter(function (s) {
        return s && s.trim();
      });
      console.log(newArr);
      this.query.checkList = newArr;
    },
    time_change(val) {
      this.query.startTime = val[0];
      this.query.endTime = val[1];
    },
    todo() {
      if (
        !this.query.dbId ||
        !this.query.addType ||
        this.query.checkList.length < 1 ||
        !this.query.startTime ||
        !this.query.endTime
      ) {
        this.$message.error("条件不全，请补充！");
        return;
      }
      let flag = this.isMsg.length == 0 ? false : true;
      let ifif = false;
      if (!flag) {
        ifif = false;
      } else if (this.isMsg[this.isMsg.length - 1].msg == "执行完毕") {
        ifif = false;
      } else if (this.isMsg[this.isMsg.length - 1].msg == "任务已经终止") {
        ifif = false;
      } else if (this.isMsg[this.isMsg.length - 1].msg == "任务暂未执行") {
        ifif = false;
      } else {
        ifif = true;
      }

      if (ifif) {
        this.$notify({
          title: "警告",
          message: "当前有程序正在执行中，请停止或待执行完毕后重试！",
          type: "warning",
        });
        return;
      }
      this.$post(
        baseUrl.jbIp + "/T1/api/v1/Platform/Collect/Collect",
        this.query
      ).then((res) => {
        this.$message({
          message: "执行中",
          type: "success",
        });
        this.query.checkList = [];
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([]);
        });
      });
    },
    stop() {
      this.$get(baseUrl.jbIp + "/T1/api/v1/Platform/Collect/Cancel").then(
        (res) => {
          this.$message({
            message: "操作成功",
            type: "success",
          });
        }
      );
    },
    init: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      this.isMsg.push({
        msg: msg.data,
        date: new Date(),
      });
      this.scrollToBottom();
      console.log(this.isMsg);
      if (this.isMsg.length > 201) {
        this.isMsg.splice(0, 1);
      }
    },
    send: function () {
      this.socket.send(params);
    },
    close: function () {
      console.log("socket已经关闭");
    },
  },
};
</script>

<style scoped lang="scss">
.SJCJ {
  padding: 20px;
  background-color: #eee;
  height: 100vh;
  .main {
    background-color: #fff;
    height: 260px;
    overflow: auto;
    margin-top: 10px;
    border: 1px solid #000;
  }
  .msg {
    padding: 5px;
    border: 1px solid #000;
    height: 450px;
    margin-top: 10px;
    overflow: auto;
    .msg_item {
      margin-bottom: 10px;
    }
  }
}
</style>
